package cdu.notFound.controller;


import cdu.notFound.model.Order;
import cdu.notFound.service.OrderService;
import cdu.notFound.service.impl.OrderServiceImpl;
import cdu.notFound.utils.LoginVerify;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 购买商品，下单
 */
@WebServlet("/OrderCheckServlet")
public class OrderCheckServlet extends HttpServlet {
   //订单验证
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String messageToSeller = request.getParameter("message-to-seller");
        Boolean isLogined = LoginVerify.isLogin(request);
        Integer userId = Integer.parseInt(request.getParameter("userid"));
        Integer goodsId = Integer.parseInt(request.getParameter("goodsid"));
        OrderService orderService = new OrderServiceImpl();
        Order order=new Order();
        //获取来源url，只保留第一个参数goodsid
       //goodsid=1
       //userid=1
        String fromURL[] = request.getHeader("Referer").split("&");
        if(isLogined!=null && isLogined==true && userId!=null && goodsId!=null){
            order.setGoodsId(goodsId);
            order.setUserId(userId);
            order.setMessage(messageToSeller);
            order.setDate(new Date());
            if(orderService.doCreate(order)){
                response.sendRedirect(fromURL[0]+"&info="+java.net.URLEncoder.encode("购买成功，消息已发送至卖家","UTF-8"));
                return;
            }
        }
        else{
            response.sendRedirect(fromURL[0]+"&info="+java.net.URLEncoder.encode("购买失败","UTF-8"));
            return;
        }
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    doGet(request, response);
	}
}
